package org.clipjoint.dao.impl;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.lang3.StringUtils;
import org.clipjoint.dao.KeyWordAdminDao;
import org.clipjoint.entity.dto.KeyWordDto;
import org.clipjoint.entity.KeyWord;
import org.clipjoint.util.DataSourceUtil;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class KeyWordAdminDaoImpl implements KeyWordAdminDao {


    @Override
    public List<KeyWordDto> selectAll(KeyWordDto keywordDto) throws SQLException {

        QueryRunner qr = new QueryRunner(DataSourceUtil.getDataSource());
        List<Object> params = new ArrayList<>();
        //动态sql
        String sql = "select * from `keyword`";


        //判断排序参数
        if (StringUtils.isNoneBlank(keywordDto.getOrderField(), keywordDto.getOrderType())) {
            sql += " order by " + keywordDto.getOrderField() + " " + keywordDto.getOrderType();
        }
        //分页参数
        if (keywordDto.getPage() != null && keywordDto.getLimit() != null) {
            sql += " limit ?,?";
            params.add((keywordDto.getPage() - 1) * keywordDto.getLimit());
            params.add(keywordDto.getLimit());

        }

        //查询所有结果
        List<KeyWordDto> result = qr.query(sql, new BeanListHandler<>(KeyWordDto.class), params.toArray());
        return result;
    }

    @Override
    public Long selectCount(KeyWordDto build) throws SQLException {
        QueryRunner qr = new QueryRunner(DataSourceUtil.getDataSource());
        //动态sql
        String sql = "select count(*) from `keyword` where 1=1";
        List<Object> params = new ArrayList<>();

        //查询一个结果
        Map<String, Object> result = qr.query(sql, new MapHandler(), params.toArray());
        return (Long) result.get("count(*)");
    }

    @Override
    public int deleteById(Long id) throws SQLException {

        QueryRunner qr = new QueryRunner(DataSourceUtil.getDataSource());
        String sql = "delete from `keyword` where `id`=?";
        int result = qr.update(sql, id);
        return result;
    }

    @Override
    public int insert(KeyWord build) throws SQLException {
        QueryRunner qr = new QueryRunner(DataSourceUtil.getDataSource());
        String sql = "insert into `keyword`(`game_id`,`keyword`,`detail`,`create_time`) value(?,?,?,?)";
        int result = qr.update(sql, build.getGame_id(),build.getKeyword(),build.getDetail(),build.getCreate_time());

        return result;
    }
}
